using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace axCommerce.Data
{
	[DataObject]
	[Serializable]
	public partial class EmailTemplateType
	{
		#region Constants

		private const string TableName = "[dbo].[EmailTemplateType]";

		#endregion

		#region Properties

		public int? EmailTemplateTypeId { get; set; }
		public string Name { get; set; }
		public int? EmailTemplateTypeCode { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("EmailTemplateTypeId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("Name", typeof (String));
			ds.Tables[TableName].Columns.Add("EmailTemplateTypeCode", typeof (Int32));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["EmailTemplateTypeId"] = EmailTemplateTypeId ?? (object) DBNull.Value;
			dr["Name"] = Name ?? (object) DBNull.Value;
			dr["EmailTemplateTypeCode"] = EmailTemplateTypeCode ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			EmailTemplateTypeId = dr["EmailTemplateTypeId"] != DBNull.Value
			                      	? Convert.ToInt32(dr["EmailTemplateTypeId"])
			                      	: EmailTemplateTypeId = null;
			Name = dr["Name"] != DBNull.Value ? Convert.ToString(dr["Name"]) : Name = null;
			EmailTemplateTypeCode = dr["EmailTemplateTypeCode"] != DBNull.Value
			                        	? Convert.ToInt32(dr["EmailTemplateTypeCode"])
			                        	: EmailTemplateTypeCode = null;
		}

		private static List<EmailTemplateType> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<EmailTemplateType> objects = new List<EmailTemplateType>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[EmailTemplateType] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[EmailTemplateType] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				var instance = new EmailTemplateType();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		internal static EmailTemplateType Get(Int32 emailTemplateTypeId)
		{
			EmailTemplateType instance = new EmailTemplateType();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateTypeId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0)
						throw new ApplicationException(String.Format("Could not get EmailTemplateType ID:{0} from Database.", emailTemplateTypeId));
					// Return results.
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(String name, Int32? emailTemplateTypeCode, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, name, emailTemplateTypeCode))
			{
				EmailTemplateTypeId = Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current EmailTemplateType to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(Name, EmailTemplateTypeCode, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? emailTemplateTypeId, String name, Int32? emailTemplateTypeCode,
		                           DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@emailTemplateTypeId"].Value = emailTemplateTypeId;
				dbCommand.Parameters["@name"].Value = name;
				dbCommand.Parameters["@emailTemplateTypeCode"].Value = emailTemplateTypeCode;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(EmailTemplateType emailTemplateType)
		{
			emailTemplateType.Update();
		}

		private static void Update(EmailTemplateType emailTemplateType, DbTransaction transaction)
		{
			emailTemplateType.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@emailTemplateTypeId"].SourceColumn = "EmailTemplateTypeId";
				dbCommand.Parameters["@name"].SourceColumn = "Name";
				dbCommand.Parameters["@emailTemplateTypeCode"].SourceColumn = "EmailTemplateTypeCode";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();
					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		#endregion

		#region DELETE

		private static void Delete(Int32? emailTemplateTypeId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateTypeId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current EmailTemplateType from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Delete(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, EmailTemplateTypeId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			EmailTemplateTypeId = null;
		}

		#endregion

		#region SEARCH

		private static List<EmailTemplateType> Search(Int32? emailTemplateTypeId = null, String name = null, Int32? emailTemplateTypeCode = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplateType_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateTypeId, name, emailTemplateTypeCode))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}


		private static List<EmailTemplateType> Search(EmailTemplateType searchObject)
		{
			return Search(searchObject.EmailTemplateTypeId, searchObject.Name, searchObject.EmailTemplateTypeCode);
		}

		#endregion

		#endregion

		#endregion
	}
}